<script setup lang="ts">
import { ref, h, onMounted, nextTick } from "vue";
import { IconifyIconOnline } from "@/components/ReIcon";
import type {
  PlusColumn,
  FieldValues,
  PlusFormInstance
} from "plus-pro-components";
import { PlusForm } from "plus-pro-components";
import { UPLOAD_IMAGE_URL } from "@/api/images";
import { ImageItem } from "types/image";
import { ElUpload } from "element-plus";
import Segmented, { OptionsType } from "@/components/ReSegmented";
import { changeUserInfo, userChangePassword } from "@/api/user";
import { message } from "@/utils/message";
import { useUserStore } from "@/store/modules/user";
import { storageLocal } from "@pureadmin/utils";
import { DataInfo, userKey } from "@/utils/auth";

const userStore = useUserStore();

const SERVER_URL = import.meta.env.VITE_SERVER_URL;

const currentTab = ref(0);
const tabOptions: Array<OptionsType> = [
  {
    label: "基本信息",
    value: 0
  },
  {
    label: "修改密码",
    value: 1
  }
];

const submitLoading = ref<boolean>(false);

const basicFormRules = {
  nickname: [
    {
      required: true,
      message: "请输入昵称"
    }
  ]
};

const basicFormColumns: PlusColumn[] = [
  {
    label: "账号",
    prop: "username",
    valueType: "input",
    fieldProps: {
      disabled: true
    }
  },
  {
    label: "昵称",
    prop: "nickname",
    valueType: "input"
  },
  {
    label: "头像",
    prop: "avatar",
    valueType: "img",
    renderField(value: string, onChange) {
      return h(
        ElUpload,
        {
          class: "avatar-uploader",
          action: UPLOAD_IMAGE_URL,
          showFileList: false,
          onSuccess: async (data: ImageItem) => {
            onChange(
              `/static/images/${data.folder}/${data.hash}.${data.format}`
            );
          }
        },
        value
          ? h("img", {
              src: SERVER_URL + value,
              class: "avatar"
            })
          : h(
              "div",
              { class: "upload-icon" },
              h(IconifyIconOnline, { icon: "ep:plus" })
            )
      );
    }
  },
  {
    label: "角色",
    prop: "roles",
    valueType: "select",
    options: [
      {
        label: "超级管理员",
        value: 1
      },
      {
        label: "管理员",
        value: 2
      }
    ],
    fieldProps: {
      disabled: true,
      multiple: true
    }
  }
];

const basicFormData = ref<FieldValues>({});

const changePasswordFormRules = {
  old_password: [
    {
      required: true,
      message: "请输入原密码"
    }
  ],
  password: [
    {
      required: true,
      validator: (_: any, value: any, callback: any) => {
        if (!value) {
          return callback(new Error("请输入密码"));
        }
        if (value.length < 6) {
          return callback(new Error("密码长度不能小于6位"));
        }
        callback();
      }
    }
  ],
  confirm_password: [
    {
      required: true,
      validator: (_: any, value: any, callback: any) => {
        if (!value) {
          return callback(new Error("请输入密码"));
        }
        if (changePasswordFormData.value.password !== value) {
          return callback(new Error("两次输入密码不一致"));
        }
        callback();
      }
    }
  ],
  roles: {
    required: true,
    message: "请选择角色"
  }
};

const changePasswordFormColumns: PlusColumn[] = [
  {
    label: "原密码",
    prop: "old_password",
    valueType: "input",
    fieldProps: {
      type: "password"
    }
  },
  {
    label: "密码",
    prop: "password",
    valueType: "input",
    fieldProps: {
      type: "password"
    }
  },
  {
    label: "确认密码",
    prop: "confirm_password",
    valueType: "input",
    fieldProps: {
      type: "password"
    }
  }
];
const changePasswordFormData = ref<FieldValues>({});

const basicFormRef = ref<PlusFormInstance>();
const handleChangeInfo = async e => {
  try {
    submitLoading.value = true;
    if (changePasswordFormData.value.id) {
      await changeUserInfo({
        nickname: e.nickname,
        avatar: e.avatar
      });
      userStore.nickname = e.nickname;
      userStore.avatar = e.avatar;
      const data = storageLocal().getItem<DataInfo<number>>(userKey);
      storageLocal().setItem(userKey, {
        ...data,
        nickname: e.nickname,
        avatar: e.avatar
      });

      nextTick(() => {
        loadFormData();
      });
      if (basicFormRef.value) {
        nextTick(() => {
          basicFormRef.value?.formInstance.resetFields();
        });
      }
      message("修改成功", { type: "success" });
    }
  } catch (e) {
    if (e.response.data && e.response.data.message) {
      message(e.response.data.message, { type: "error" });
    } else {
      message("修改失败", { type: "error" });
    }
    console.log(e);
  } finally {
    submitLoading.value = false;
  }
};

const changePasswordFormRef = ref<PlusFormInstance>();
const handleChangePassword = async e => {
  try {
    submitLoading.value = true;
    if (changePasswordFormData.value.id) {
      await userChangePassword({
        old_password: e.old_password,
        password: e.password
      });
      loadFormData();
      if (changePasswordFormRef.value) {
        nextTick(() => {
          changePasswordFormRef.value?.formInstance.resetFields();
        });
      }
      message("修改成功", { type: "success" });
    }
  } catch (e) {
    if (e.response.data && e.response.data.message) {
      message(e.response.data.message, { type: "error" });
    } else {
      message("修改失败", { type: "error" });
    }
    console.log(e);
  } finally {
    submitLoading.value = false;
  }
};

const loadFormData = () => {
  basicFormData.value = {
    id: userStore.id,
    username: userStore.username,
    nickname: userStore.nickname,
    avatar: userStore.avatar,
    roles: userStore.roles
  };

  changePasswordFormData.value = {
    id: userStore.id
  };
};

onMounted(() => {
  loadFormData();
});
</script>
<template>
  <div>
    <el-card shadow="never">
      <template #header>
        <div class="flex justify-between items-center">
          <span>账号信息</span>

          <el-space>
            <Segmented v-model="currentTab" :options="tabOptions" />
          </el-space>
        </div>
      </template>
      <PlusForm
        v-if="currentTab === 0"
        ref="basicFormRef"
        v-model="basicFormData"
        :columns="basicFormColumns"
        :rules="basicFormRules"
        footer-align="right"
        label-position="top"
        :has-reset="false"
        :submit-loading="submitLoading"
        @submit="handleChangeInfo"
      />
      <PlusForm
        v-if="currentTab === 1"
        ref="changePasswordFormRef"
        v-model="changePasswordFormData"
        :columns="changePasswordFormColumns"
        :rules="changePasswordFormRules"
        footer-align="right"
        label-position="top"
        :has-reset="true"
        :submit-loading="submitLoading"
        @submit="handleChangePassword"
      />
    </el-card>
  </div>
</template>
<style lang="scss">
.avatar-uploader {
  .avatar {
    width: 168px;
    height: 168px;
    display: block;
  }

  .el-upload {
    border: 1px dashed var(--el-border-color);
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    transition: var(--el-transition-duration-fast);
  }

  .avatar-uploader .el-upload:hover {
    border-color: var(--el-color-primary);
  }

  .upload-icon {
    font-size: 28px;
    color: #8c939d;
    width: 168px;
    height: 168px;
    display: flex;
    align-items: center;
    justify-content: center;
  }
}
</style>
